# -*- coding: utf-8 -*-
# standard
import os
import sys

# third
import requests

# local
_P_PATH =  os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
if _P_PATH not in sys.path:
    sys.path.append(_P_PATH)
from models.iot_model import *


"""
@Title:   微服务的功能函数 每个微服务中都有此函数， 但有些差异
@File: mic_service_func.py
@Author: walle 2025年01日02日 15时03分24秒
@Version: 1.0.0
@Desc: 
"""


def sync_store_names():
    """
    同步店铺名称和品牌名称 仅在需要同步的时候手动运行
    :return:
    """
    
    db_session = new_db_session()
    s = select(
        SensorOrm.store_id, 
    ).where(
        or_(
            SensorOrm.store_name == None,
            SensorOrm.customer_name == None
        )
    )
    ids = db_session.scalars(s).all()
    db_session.close()
    auth = "Bearer 9a012eae442a9c16c90911f71d8709e2"
    url = "http://127.0.0.1:8088/v1/customer/store/base_info/get_by_ids"
    headers = {
        "Authorization": auth
    }
    kw = {"ids": ids}
    resp = requests.post(url, headers=headers, json=kw)
    resp = resp.json()
    a_map = {x['store_id']: x for x in resp['data']}
    db_session = new_db_session()
    s = select(
        SensorOrm, 
    ).where(
        or_(
            SensorOrm.store_name == None,
            SensorOrm.customer_name == None
        )
    )
    for x in db_session.scalars(s).all():
        x.store_name = a_map[x.store_id]['store_name']
        x.customer_name = a_map[x.store_id]['customer_name']
    db_session.commit()
    db_session.close()
    return

if __name__ == '__main__':
    sync_store_names()
    pass